package com.dadaguai.controller;

import com.dadaguai.annotation.JwtToken;
import com.dadaguai.common.BusinessException;
import com.dadaguai.common.R;
import com.dadaguai.constants.CaptchaConstants;
import com.dadaguai.constants.ResponseCode;
import com.dadaguai.service.EmailCodeService;
import com.dadaguai.service.UserInfoService;
import com.dadaguai.utils.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@RestController
public class CaptchaController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    EmailCodeService emailCodeService;

    /**
     * 验证码校验
     *
     * @param code 验证码
     * @param type 验证码类型 0=图片验证码；1=邮箱验证码
     */
    @GetMapping("/checkCode")
    public R checkCode(@RequestParam String code, @RequestParam Integer type, @RequestParam String email) {
        return emailCodeService.checkCode(code, type, email);
    }

    /**
     * 发送图片验证码
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/sendImgCode")
    public void sendImgCode(HttpServletResponse response, @RequestParam String email ) throws IOException {

        //outputVerifyImage此方法可以获得一个图片验证码，并返回验证码中的验证数值，可以用前台传过来的验证码与之进行比对
        //                                          宽度    高度       输出流   几个位数的验证码
        String code = Captcha.outputVerifyImage(100, 40, response.getOutputStream(), 4);
        stringRedisTemplate.opsForValue().set(CaptchaConstants.IMG_CODE_KEY + email, code, 3, TimeUnit.MINUTES);
    }

    /**
     * 发送邮箱验证码
     *
     * @param email 邮件接收地址
     * @param type 邮件类型 0-注册邮件，1-修改密码邮件
     * @return
     * @throws BusinessException
     */

    @GetMapping("/sendEmailCode")
    public R sendEmailCode(@RequestParam String email ,@RequestParam Integer type) throws BusinessException {
        Boolean result = emailCodeService.sendEmailCode(email,type);
        if (!result) {
            return R.error("邮箱未注册", ResponseCode.USER_HANDLE_ERROR);
        }
        return R.success("验证码发送成功");
    }
}
